package com.ds.infrastructure.hyperspace.console.dto.apirouter;

import com.alibaba.fastjson.annotation.JSONField;
import com.ds.infrastructure.hyperspace.console.dto.configdata.PreflowDTO;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: yaozhendong
 * @create: 2019-09-20 16:13
 **/
@Data
@NoArgsConstructor
public class ApiRouterPreflowDTO implements Serializable {
    private String handler;
    @JSONField(name = "handlerParams")
    private List<String> handlerParams = new ArrayList<>();

    public static ApiRouterPreflowDTO toApiRouter(PreflowDTO dto) {
        ApiRouterPreflowDTO apiRouterPreflowDTO = new ApiRouterPreflowDTO();
        apiRouterPreflowDTO.setHandler(dto.getHandler());
        addHandlerParams(apiRouterPreflowDTO, dto);
        return apiRouterPreflowDTO;
    }

    /**
     * HandlerParams默认是字符串，通过英文逗号进行分组
     *
     * @param apiRouterPreflowDTO
     * @param dto
     */
    private static void addHandlerParams(ApiRouterPreflowDTO apiRouterPreflowDTO, PreflowDTO dto) {
        if (dto.getHandlerparams() == null || dto.getHandlerparams().isEmpty()) {
            return;
        }
        for (String handlerParam : dto.getHandlerparams()) {
            if (StringUtils.isBlank(handlerParam)) {
                continue;
            }
            for (String item : handlerParam.split(",")) {
                apiRouterPreflowDTO.getHandlerParams().add(item.trim());
            }
        }
    }
}
